<template>
  <console-global-layout @dynamicRouterShow="dynamicRouterShow">
    <contextmenu :itemList="menuItemList" :visible.sync="menuVisible" style="z-index: 9999;" @select="onMenuSelect"/>
    <a-tabs
      v-if="multipage"
      :active-key="activePage"
      class="labelPage"
      @change="changePage"
      @tabClick="tabCallBack">

      <a-tab-pane v-for="(item, index) in pageList" :key="item.fullPath">
        <template slot="tab">
          <span
            @contextmenu.prevent="onContextmenu($event, index)"
            :title="item.meta.title">
            <a-icon v-if="item.meta.icon" :type="item.meta.icon" />
            {{ item.meta.title }}
          </span>
          <a-icon
            v-if="pageList.length > 1"
            type="close"
            style="padding-left: 6px; position: relative; top: -14px"
            @click.stop="remove(item.fullPath)"
          />
        </template>
      </a-tab-pane>

    </a-tabs>
    <transition name="page-toggle">
      <div style="height: calc(100vh - 150px);" class="main">
        <keep-alive>
          <router-view v-if="isRouterAlive" :key="$route.fullPath" ref="page"/>
        </keep-alive>
        <component
          v-for="iframe in iframeKeepAlives"
          :key="iframe.fullPath"
          :meta="iframe.meta"
          :is="iframe.meta.componentName"
          v-show="iframe.fullPath === $route.fullPath"
        ></component>
      </div>
    </transition>
  </console-global-layout>
</template>

<script>
  import Vue from 'vue'
  import VueRouter from 'vue-router'
  import ConsoleGlobalLayout from './ConsoleGlobalLayout'
  import Contextmenu from '../menu/Contextmenu'
  import { mixinDevice } from '@/utils/mixin.js'
  import { triggerWindowResizeEvent } from '@/utils/util'
  import {randomString} from '../../utils/util'

  export default {
    name: 'ConsoleTabLayout',
    components: {
      ConsoleGlobalLayout,
      Contextmenu
    },
    mixins: [mixinDevice],
    data () {
      return {
        pageList: [],
        pagekey: null, // 右键页签
        linkList: [],
        activePage: '',
        menuVisible: false,
        menuItemList: [
          { key: '4', icon: 'reload', text: this.$t('m.common.button.refresh') },
          { key: '1', icon: 'arrow-left', text: this.$t('m.common.button.close_left') },
          { key: '2', icon: 'arrow-right', text: this.$t('m.common.button.close_right') },
          { key: '3', icon: 'close', text: this.$t('m.common.button.close_other') }
        ],
        isRouterAlive: true,
      }
    },
    provide () {
      return {
        closeCurrent: this.closeCurrent,
        addRouter: this.addRouter,
        removeCache: this.removeCache,
      }
    },
    computed: {
      iframeKeepAlives(){
        return this.$store.state.permission.iframeKeepAlives
      },
      keepAlives(){
        return this.$store.state.permission.keepAlives
      },
      tempRouterFullPath(){
        return this.$store.state.permission.tempRouterFullPath
      },
      multipage () {
        //判断如果是手机模式，自动切换为单页面模式
        if (this.isMobile()) {
          return false
        } else {
          return true
        }
      }
    },
    created () {
      let storeKey = 'route:title:' + this.$route.fullPath
      let routeTitle = this.$ls.get(storeKey)
      if (routeTitle) {
        this.$route.meta.title = routeTitle
      }
      this.pageList.push(this.$route)
      this.$store.commit("SET_KEEPALIVES", this.pageList)
      this.linkList.push(this.$route.fullPath)
      this.activePage = this.$route.fullPath

      Vue.prototype.dynamicRouterShow = this.dynamicRouterShow
      Vue.prototype.getLinkList = this.getLinkList
    },
    watch: {
      '$route': function (newRoute, oldRoute) {
        //console.log('当前监听的路由',newRoute,oldRoute)
        //通过#的不跳转页面
        if (newRoute.fullPath.indexOf('#') !== -1) {
          return
        }
        this.activePage = newRoute.fullPath
        if (!this.multipage) {
          this.linkList = [newRoute.fullPath]
          this.pageList = [Object.assign({}, newRoute)]
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if (this.linkList.indexOf(newRoute.fullPath) < 0) {
          this.linkList.push(newRoute.fullPath)
          this.pageList.push(Object.assign({}, newRoute))
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if (this.linkList.indexOf(newRoute.fullPath) >= 0) {
          let oldIndex = this.linkList.indexOf(newRoute.fullPath)
          let oldPositionRoute = this.pageList[oldIndex]
          this.pageList.splice(oldIndex, 1, Object.assign({}, newRoute, { meta: oldPositionRoute.meta }))
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if(newRoute.meta.isIframe && !newRoute.meta.keepAlive){
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        }

        if(oldRoute && !oldRoute.meta.keepAlive){
          this.removeCache(oldRoute.fullPath)
        }
      },
      'activePage': function (key) {
        let index = this.linkList.lastIndexOf(key)
        let waitRouter = this.pageList[index]
        this.$router.push(Object.assign({}, waitRouter)).catch(err => {})
        this.changeTitle(waitRouter.meta.title)
      },
      'multipage': function (newVal) {
        if (!newVal) {
          this.linkList = [this.$route.fullPath]
          this.pageList = [this.$route]
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        }
      },
      keepAlives(newVal, oldVal) {
        const removeVal = oldVal.filter(item => newVal.indexOf(item) === -1);
        removeVal.forEach(item => {
          this.removeCache(item)
        })
      },
      tempRouterFullPath(newVal, oldVal) {
        // 还有问题未解决
        // const removeVal = oldVal.filter(item => newVal.indexOf(item) === -1);
        // if (removeVal.length > 0) {
        //   // 删掉动态路由，官方暂不支持，此为替代方案
        //   // 获取原始路由数据配置
        //   const options = this.$router.options
        //
        //   // 用原始数据重新 new 一个路由
        //   const _VueRouter = new VueRouter(options)
        //
        //   // 用新路由的 matcher 替换旧路由的 matcher
        //   this.$router.matcher = _VueRouter.matcher
        //
        //   // 还原路由规则
        //   this.$store.getters.addRouters.forEach(routeItem => {
        //     this.$router.addRoute(routeItem)
        //   })
        //   this.$store.state.permission.tempRouters.forEach(routeItem => {
        //     this.$router.addRoute(routeItem)
        //   })
        // }
      },
    },
    methods: {
      addRouter(router, isNew) {
        if (isNew) {
          router.path = router.path + "/" + randomString(8)
        }
        router.path = '/tempRouter' + router.path
        const rootPath = router.path + '/index'
        const oldRouter = this.$router.getRoutes().find(item => item.path === rootPath)
        if (oldRouter) {
          return router.path
        }
        router.meta.tempRouter = true
        router.meta.keepAlive = true
        router.meta.parentFullPath = this.$route.fullPath
        router.meta.rootPath = rootPath
        const indexRouter = {
          path: rootPath,
          component: resolve => require(['@/framework/console/ConsoleTabLayout'], resolve),
          children: [router]
        }
        this.$router.addRoute(indexRouter)
        this.$store.commit("ADD_TEMPROUTER", indexRouter)
        return router.path
      },
      getLinkList () {
        return this.linkList
      },
      changeTitle (title) {
        let projectTitle = window._CONFIG.full_name || this.$t('m.logo.full_name')
        document.title = title + ' · ' + projectTitle
      },
      changePage (key) {
        //console.log('当前标签页的key',key)
        this.activePage = key
      },
      tabCallBack () {
        this.$nextTick(() => {
          triggerWindowResizeEvent()
        })
      },
      remove (key) {
        if (this.pageList.length === 1) {
          this.messageUtil.warning('这是最后一页，不能再关闭了啦')
          return
        }
        this.pageList = this.pageList.filter(item => item.fullPath !== key)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        let index = this.linkList.indexOf(key)
        this.linkList = this.linkList.filter(item => item !== key)
        index = index >= this.linkList.length ? this.linkList.length - 1 : index
        this.activePage = this.linkList[index]
      },
      onContextmenu (e, index) {
        this.pagekey = this.pageList[index].fullPath
        if (this.pagekey !== null) {
          e.preventDefault()
          this.menuVisible = true
        }
      },
      onMenuSelect (key, target) {
        let pageKey = this.pagekey
        switch (key) {
        case '1':
          this.closeLeft(pageKey)
          break
        case '2':
          this.closeRight(pageKey)
          break
        case '3':
          this.closeOthers(pageKey)
          break
        case '4':
          this.routeReload(pageKey)
          break
        default:
          break
        }
      },
      closeCurrent () {
        this.remove(this.activePage)
      },
      closeOthers (pageKey) {
        let index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(index, index + 1)
        this.pageList = this.pageList.slice(index, index + 1)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        this.activePage = this.linkList[0]
      },
      closeLeft (pageKey) {
        let index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(index)
        this.pageList = this.pageList.slice(index)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        if (this.linkList.indexOf(this.activePage) < 0) {
          this.activePage = this.linkList[0]
        }
      },
      closeRight (pageKey) {
        let index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(0, index + 1)
        this.pageList = this.pageList.slice(0, index + 1)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        if (this.linkList.indexOf(this.activePage < 0)) {
          this.activePage = this.linkList[this.linkList.length - 1]
        }
      },
      dynamicRouterShow (key, title) {
        let keyIndex = this.linkList.indexOf(key)
        if (keyIndex >= 0) {
          let currRouter = this.pageList[keyIndex]
          let meta = Object.assign({}, currRouter.meta, { title: title })
          this.pageList.splice(keyIndex, 1, Object.assign({}, currRouter, { meta: meta }))
          this.$store.commit("SET_KEEPALIVES", this.pageList)
          if (key === this.activePage) {
            this.changeTitle(title)
          }
        }
      },

      routeReload(pageKey) {
        // 清除缓存
        let indexFullPath = this.linkList.indexOf(pageKey)
        let fullPath = this.pageList[indexFullPath].fullPath;

        this.removeCache(fullPath)

        this.isRouterAlive = false;

        this.$nextTick(() => {
          this.isRouterAlive = true;
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        })
      },
      removeCache(fullPath){
        if (this.$refs.page) {
          const {
            cache, keys
          } = this.$refs.page.$vnode.parent.componentInstance
          if (cache[fullPath]) {
            delete cache[fullPath]
          }

          const index = keys.indexOf(fullPath)
          if (index > -1) {
            keys.splice(index, 1)
          }
        }
        this.$store.commit("REMOVE_IFRAMEKEEPALIVES", fullPath)
      },
    }
  }
</script>

<style lang="less">

/* 主题标签页高度 */
@theme-tab-height: 36px;
@theme-tab-height-2: 36px;
// 定义字体大小
@theme-con-font-12: 12px;

.labelPage {
  height: @theme-tab-height;
  // border-bottom:1px solid #e8e8e8;
  position: relative;
  z-index: 10;
  background: #f0f2f5;
  .ant-tabs {
    height: 40px;
  }
  .ant-btn {
    border: none;
    background: none;
    font-size: @theme-con-font-12;
    float: left;
    line-height: @theme-tab-height;
    color: #888;
    padding-left: 30px;
    overflow: hidden;
  }
  .ant-tabs-bar {
    margin: 0;
    border: none;
  }
  .ant-tabs-nav-wrap{
    margin: 0;
  }
  .ant-tabs-nav .ant-tabs-tab:first-child {
    padding: 0 16px ;
    border-left:1px solid #e8e8e8 ;
    .anticon-home{
      font-size: 14px;
      margin-right: 4px;
    }
    .close-icon{
      display: none;
    }
  }
  .ant-tabs-nav .ant-tabs-tab {
    font-size: 14px;
    height: @theme-tab-height;
    padding: 0 4px 0 16px;
    border: 0;
    margin: 0;
    color: #888;
    vertical-align: top;
    transition:none;
    border-right:1px solid #e8e8e8 ;
    // box-shadow: rgba(62, 57, 107, 0.1) 0 2px 6px 0;
    &.ant-tabs-tab-active{
      font-weight: normal;
      background: #e8edf7;
    }
    span {
      //   限制标签页最大宽度 溢出变省略号
      display: inline-block;
      max-width: 112px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      line-height: @theme-tab-height-2;
    }
    .close-icon {
      position: absolute;
      top: 13px;
      right: 10px;
      opacity: 1 !important;
      color: #8594aa;
      margin-right: 4px;
    }
    .close-icon:hover{
      color: red;
    }
  }
  .ant-tabs-ink-bar {
    height: 4px;
    display: none !important;
  }
  .ant-tabs-tab-prev.ant-tabs-tab-arrow-show,
  .ant-tabs-tab-next.ant-tabs-tab-arrow-show{
    width: 36px;
  }
  .ant-tabs-nav-container-scrolling{
    padding-right: 36px;
    padding-left: 36px;
  }
  .ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
    font-weight: normal;
    border: 0;
  }
}
</style>
